

package com.zdkj.subway.epm.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.epm.entity.SwExCheckFault;
import com.zdkj.subway.epm.service.SwExCheckFaultService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;


/**
 * 票务稽查问题处理
 *
 * @author cuilei
 * @date 2020-05-26 15:05:50
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swexcheckfault")
@Api(value = "swexcheckfault", tags = "票务稽查问题处理管理")
public class SwExCheckFaultController {
    //通知状态
    private final static String NOTICE_STATUS_NO = "0";
    private final static String NOTICE_STATUS_YES = "1";
    private final static String NOTICE_STATUS_Re = "2";
    //反馈状态
    private final static String BACK_STATUS_NO = "0";
    private final static String BACK_STATUS_YES = "1";

    private final SwExCheckFaultService swExCheckFaultService;

    /**
     * 分页查询
     *
     * @param page           分页对象
     * @param swExCheckFault 票务稽查问题处理
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwExCheckFaultPage(Page page,String startDate, String endDate, SwExCheckFault swExCheckFault) {
        IPage selList;
        if (SecurityUtils.getUser().getBelongToLine()) {
            if(StringUtils.isEmpty(startDate)){
                selList = swExCheckFaultService.page(page, Wrappers.query(swExCheckFault));
            }else{
                selList = swExCheckFaultService.page(page, Wrappers.query(swExCheckFault)
                        .apply("DATE_FORMAT(CHECK_TIME,'%Y-%m-%d') between '"+startDate+"' and '"+endDate+"'"));
            }
        }else{
            if(StringUtils.isEmpty(startDate)){
                selList = swExCheckFaultService.page(page, Wrappers.query(swExCheckFault)
                        .lambda().eq(SwExCheckFault::getLineCode, SecurityUtils.getUser().getLineCode())
                        .eq(SwExCheckFault::getStationCode, SecurityUtils.getUser().getStationCode())
                        .and(i -> i.eq(SwExCheckFault::getNoticeStatus, NOTICE_STATUS_YES).or()
                                .eq(SwExCheckFault::getNoticeStatus, NOTICE_STATUS_Re)));
            }else{
                selList = swExCheckFaultService.page(page, Wrappers.query(swExCheckFault)
                        .lambda().eq(SwExCheckFault::getLineCode, SecurityUtils.getUser().getLineCode())
                        .eq(SwExCheckFault::getStationCode, SecurityUtils.getUser().getStationCode())
                        .and(i -> i.eq(SwExCheckFault::getNoticeStatus, NOTICE_STATUS_YES).or()
                                .eq(SwExCheckFault::getNoticeStatus, NOTICE_STATUS_Re))
                        .apply("DATE_FORMAT(CHECK_TIME,'%Y-%m-%d') between '"+startDate+"' and '"+endDate+"'"));
            }
        }
        return R.ok(selList);
    }

    /**
     * 通过id查询票务稽查问题处理
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swExCheckFaultService.getById(id));
    }

    /**
     * 新增票务稽查问题处理
     *
     * @param swExCheckFault 票务稽查问题处理
     * @return R
     */
    @ApiOperation(value = "新增票务稽查问题处理", notes = "新增票务稽查问题处理")
    @SysLog("新增票务稽查问题处理")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('epm_sw_ex_check_fault_add')")
    public R save(@RequestBody SwExCheckFault swExCheckFault) {
        SwExCheckFault defaultObj = ObjectUtils.getDefaultObj(SwExCheckFault.class);
        BeanUtils.copyProperties(swExCheckFault, defaultObj,
                ObjectUtils.getNullAndEmptyPropertyNames(swExCheckFault));
        defaultObj.setDeptId(SecurityUtils.getUser().getDeptId());
        return R.ok(swExCheckFaultService.save(defaultObj));
    }

    /**
     * 修改票务稽查问题处理
     *
     * @param swExCheckFault 票务稽查问题处理
     * @return R
     */
    @ApiOperation(value = "修改票务稽查问题处理", notes = "修改票务稽查问题处理")
    @SysLog("修改票务稽查问题处理")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('epm_sw_ex_check_fault_edit')")
    public R updateById(@RequestBody SwExCheckFault swExCheckFault) {
        return R.ok(swExCheckFaultService.updateById(swExCheckFault));
    }

    /**
     * 通过id删除票务稽查问题处理
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除票务稽查问题处理", notes = "通过id删除票务稽查问题处理")
    @SysLog("通过id删除票务稽查问题处理")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('epm_sw_ex_check_fault_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swExCheckFaultService.removeById(id));
    }

    /**
     * 票务稽查问题批量通知
     *
     * @param swExCheckFault 票务稽查问题
     * @return R
     */
    @ApiOperation(value = "票务稽查问题批量通知", notes = "票务稽查问题批量通知")
    @SysLog("票务稽查问题批量通知")
    @PutMapping("noticeBatch")
    @PreAuthorize("@pms.hasPermission('epm_sw_ex_check_fault_noticeBatch')")
    public R noticeBatch(@RequestBody List<SwExCheckFault> swExCheckFault) {
        if (SecurityUtils.getUser().getBelongToLine()) {
            for (SwExCheckFault e : swExCheckFault) {
                e.setNoticeTime(LocalDate.now());
                e.setNoticeStatus(NOTICE_STATUS_YES);
            }
            return R.ok(swExCheckFaultService.updateBatchById(swExCheckFault));
        } else {
            for (SwExCheckFault e : swExCheckFault) {
                if (e.getNoticeStatus().equals(NOTICE_STATUS_YES)) {
                    e.setBackTime(LocalDate.now());
                    e.setNoticeStatus(NOTICE_STATUS_Re);
                    e.setBackStatus(BACK_STATUS_YES);
                }
            }
            return R.ok(swExCheckFaultService.updateBatchById(swExCheckFault));
        }
    }
    /**
     * 导出票务稽查问题处理
     *
     * @param page
     * @param swExCheckFault
     * @param response
     * @return
     */
    @ApiOperation(value = "导出票务稽查问题处理", notes = "导出票务稽查问题处理")
    @SysLog("导出票务稽查问题处理")
    @GetMapping("/export")
    public void exportExcel(Page page, SwExCheckFault swExCheckFault, HttpServletResponse response) {
        List exportList = new ArrayList();
        if(CollectionUtil.isNotEmpty(swExCheckFault.getIds())){
            for (Integer item : swExCheckFault.getIds()){
                QueryWrapper<SwExCheckFault> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(SwExCheckFault::getId,item);
                wrapper.select("id,(select spl.`name` from sw_param_line spl where spl.`code` = sw_ex_check_fault.line_code) as line_code," +
                        "(select sps.`name` from sw_param_station sps where sps.line_code = sw_ex_check_fault.line_code and sps.`code` = sw_ex_check_fault.station_code) as station_code," +
                        "check_time,checked_person_name,checked_person_code,check_person_name,check_person_code,notice_time,back_time_limit,back_time,feedback_result,problem_content");
                SwExCheckFault data = swExCheckFaultService.getOne(wrapper);
                exportList.add(data);
            }
        }else{
            if (SecurityUtils.getUser().getBelongToLine()) {
                QueryWrapper<SwExCheckFault> wrapper = Wrappers.query(swExCheckFault);
                wrapper.select("id,(select spl.`name` from sw_param_line spl where spl.`code` = sw_ex_check_fault.line_code) as line_code," +
                        "(select sps.`name` from sw_param_station sps where sps.line_code = sw_ex_check_fault.line_code and sps.`code` = sw_ex_check_fault.station_code) as station_code," +
                        "check_time,checked_person_name,checked_person_code,check_person_name,check_person_code,notice_time,back_time_limit,back_time,feedback_result,problem_content");
                exportList = swExCheckFaultService.page(page, wrapper).getRecords();
            }else{
                QueryWrapper<SwExCheckFault> wrapper = Wrappers.query(swExCheckFault)
                        .eq("line_code",SecurityUtils.getUser().getLineCode())
                        .eq("station_code",SecurityUtils.getUser().getStationCode());
                wrapper.select("id,(select spl.`name` from sw_param_line spl where spl.`code` = sw_ex_check_fault.line_code) as line_code," +
                        "(select sps.`name` from sw_param_station sps where sps.line_code = sw_ex_check_fault.line_code and sps.`code` = sw_ex_check_fault.station_code) as station_code," +
                        "check_time,checked_person_name,checked_person_code,check_person_name,check_person_code,notice_time,back_time_limit,back_time,feedback_result,problem_content");
                exportList = swExCheckFaultService.page(page, wrapper).getRecords();
            }
        }
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("票务稽查问题处理", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwExCheckFault.class).
                    sheet("票务稽查问题处理").doWrite(exportList);
        } catch (IOException e) {
            log.info(e.getMessage());
        }
    }
}
